package com.wanban.download.utils

import android.content.Context
import android.content.SharedPreferences
import com.wanban.download.ContextProvider
import com.wanban.download.model.DownloadType
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty

class VideoDownloadSPUtil {

    companion object {

        const val NAME = "video_download_sp"

        val instance: VideoDownloadSPUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            VideoDownloadSPUtil()
        }

        fun getSPUtils(): SharedPreferences {
            return ContextProvider.application.getSharedPreferences(NAME, Context.MODE_PRIVATE)
        }
    }
    /**
     * 是否只允许wifi下载，默认true
     */
    var isDownloadOnlyWIFI: Boolean by PreferenceDelegate("isDownloadOnlyWIFI", true)
    /**
     * 是否使用sdcard下载
     */
    var isUseSdcardDownload: Boolean by PreferenceDelegate("isUseSdcardDownload", false)
    /**
     * 当前下载器类型
     */
    var currentDownloadType: Int by PreferenceDelegate("currentDownloadType", DownloadType.MEDIA3)


    fun clear() {
        PreferenceDelegate("", 0L).clear()
    }

    @Suppress("UNCHECKED_CAST")
    class PreferenceDelegate<T>(private val propName: String, private val defaultValue: T) : ReadWriteProperty<Any, T> {

        private val sharedPreferences: SharedPreferences by lazy {
            ContextProvider.application.getSharedPreferences(NAME, Context.MODE_PRIVATE)
        }

        fun clear() {
            sharedPreferences.edit().clear().apply()
        }

        override fun setValue(thisRef: Any, property: KProperty<*>, value: T) {
            value?.let { putSPValue(propName, value) }
        }

        override fun getValue(thisRef: Any, property: KProperty<*>): T {
            return getSPValue(propName, defaultValue) ?: defaultValue
        }

        private fun <T> getSPValue(name: String, defaultValue: T): T? = with(sharedPreferences) {
            val result = when (defaultValue) {
                is String -> getString(name, defaultValue)
                is Int -> getInt(name, defaultValue)
                is Long -> getLong(name, defaultValue)
                is Float -> getFloat(name, defaultValue)
                is Boolean -> getBoolean(name, defaultValue)
                else -> null
            }
            result as T
        }

        private fun <T> putSPValue(name: String, value: T) = with(sharedPreferences.edit()) {
            when (value) {
                is Long -> putLong(name, value)
                is String -> putString(name, value)
                is Int -> putInt(name, value)
                is Boolean -> putBoolean(name, value)
                is Float -> putFloat(name, value)
                else -> null
            }
        }?.apply()
    }



}

